<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 *
 *
 */
class json extends CI_Model  {
	/**
	 * Constructor
	 * @access protected
	 */
	function _construct()
	{
		// Call the Model constructor
		parent::_construct();
	}
	function get()
	{
		$y=2011;
		$m=12;
		$n=($m!=2?(($m%2)^($m>7))+30:(!($y%400)||!($y%4)&&($y%25)?29:28));
		$dateS=$y."-".$m."-01";
		$dateE=$y."-".$m."-".$n;
		$id=38;
		
		$query="Select idStruct from listoftables where id=".$id;
		$result=$this->db->query($query);
		if($result->num_rows()>0)
		{
			$idstruct=$result->row()->idStruct;
		}
		else{$this->log('getPrice Error table id='.$id);return false;}
		$query="Select idrow from liststruct where idStruct=".$idstruct;
		$result=$this->db->query($query);
		$i=0;
		foreach($result->result() as $row)
		{
			$query="Select id,name,`desc` from rows where id=".$row->idrow;
			$rowsName=$this->db->query($query);
			if($rowsName->num_rows()>0)
			{
				$row=$rowsName->row();
				$struct[$i]['id']=$row->id;
				$struct[$i]['name']=$row->name;
				$struct[$i]['desc']=$row->desc;
				$i++;
			}
		}
		$query="Select `Date`,`price`,`idRow` from price where idTable=".$id." and `date`>='$dateS' and `date`<='$dateE'";
		$result=$this->db->query($query);
		$i=0;
		$DATA=array();
		$i=0;
		foreach($result->result() as $row)
		{
			$DATA[$i]['price']=$row->price;
			$DATA[$i]['date']=$row->Date;
			$DATA[$i]['idRow']=$row->idRow;
			$i++;
		}
		
		
		for($i=0;$i<count($struct);$i++)
		{
			$rows[$i]['cell']=array($struct[$i]['id'],$struct[$i]['name'],$struct[$i]['desc']);
			for($j=3;$j<=$n+2;$j++)
			{
				if($price=$this->_search($j-1,$m,$y,$struct[$i]['id'],$DATA))
				{
					$rows[$i]['cell'][$j]=$price==0?"":$price;
				}
				else
				{
					$rows[$i]['cell'][$j]="";
				}
			}
		}
		$responce->rows=$rows;
		$this->db->close();
		return json_encode($responce);
	}
	function _search($dd,$mm,$yyyy,$idRow,$DATA)
	{
		$date=$yyyy;
		if (strlen ($mm)<2) {
			$date.="-0".$mm;
		}
		else
		{
			$date.="-".$mm;
		}
		if (strlen ($dd)<2) {
			$date.="-0".$dd;
		}
		else
		{
			$date.="-".$dd;
		}
		for ($i=0;$i<count($DATA);$i++)
		{
		if(strcmp ($DATA[$i]['date'],$date)==0&&$DATA[$i]['idRow']==$idRow)//
		{
		return $DATA[$i]['price'];
				}
		}
		return false;
	}
}